class Solution {
private:
    static bool cmp(pair<string, int>& a, pair<string, int>& b){
        if(a.second != b.second)return a.second > b.second;
        return a.first < b.first;
    }
public:
    vector<string> topKFrequent(vector<string>& words, int k) {
        unordered_map<string, int> mp;
        for(int i = 0; i < words.size(); i++){
            if(mp.find(words[i]) == mp.end())mp[words[i]] = 1;
            else mp[words[i]]++;
        }
        vector<pair<string, int>> ans;
        for(auto item : mp){
            ans.push_back(pair<string, int>(item.first, item.second));
        }
        sort(ans.begin(), ans.end(), cmp);
        vector<string>res;
        for(int i = 0; i < k; i++){
            res.push_back(ans[i].first);
        }
        return res;
    }
};
//2021.5.20 
